<?php
namespace Index\Controller;
use Think\Controller;
use Org\Util\Wechat;
header("Content-type: text/html; charset=utf-8"); 
class KefuController extends Controller{
	
	private $WX = null;
	private $kf_account = null;
 	private $user_id = 0;

	public function saveTmp(){
		$openid = session('openid');  //提问者的OPENID
		$key = I('post.key');
		//默认中心ID为1
		$scid = 1;
		$kf_ids = M('ScManager')->field('user_id')->where(array('sc_id'=>$scid))->select();
		$kfIdx = mt_rand(0,count($kf_ids))-1;
		$kfIdx = $kfIdx>=0 ? $kfIdx : 0;
		$kfid = $kf_ids[$kfIdx]['user_id'];
		$muser = M('RbacManager')->where(array('id'=>$kfid))->find();
		$kfuser = M('Kf')->where(array('openid'=>$muser['openid']))->find();
		$data = array(
			'openid'		=>	$openid,
			'key'			=>	$key,
			'kf_account'	=>	$kfuser['kf_account'],
			'created'		=>  time(),
		);

		$Md = M('Kf_tmp_key');
		$hasData = $Md->where(array('openid'=>$openid,'kf_account'	=>	''))->count();
		//存在即更新
		if($hasData){
			$rs = $Md->where(array('openid'=>$openid,'kf_account'	=>	''))->save($data);
		}else{
			$rs = $Md->data($data)->add();
		}


		//对接客服
		$st = true;
		if($rs && $st){
			$this->_ajax(true,'OK');
		}else{
			$this->_ajax(false,'Error');
		}
	}
	
	public function _initialize(){ 
		$this->WX = new Wechat(C('test')); 
		$openid = session('openid'); 
		// $openid = 'oYCoAxGxGuStdFwAqo7KaogDKPtI';
		// session('openid', $openid);
		if(!empty(I('get.openid'))){
			session('toUserToOpenid',I('get.openid'));
		}
		
		if (empty($openid) && ACTION_NAME != 'wlg') { 
			 header('location:'.'/index.php/Kefu/wlg');
		} 

		$kf = M('Kf')->where(array('openid'=>$openid))->find();
	
		session('kf_account',$kf['kf_account']);

		$this->kf_account = session('kf_account');

        $customer=M('customer')->where('openid="'.$openid.'"')->find();
        if (empty($customer)) {
            $this->redirect('../index.php/Register/index');
        }
        $this->user_id = $customer['id'];
	}
	
	
	function wlgout(){
		session_destroy();
		session(null);
		exit('Logout OK ');
	} 
	
	function wlg(){
        $callback = 'http://sunwayuchoice.com/index.php/Kefu/lgback';
        $url = $this->WX->getOauthRedirect($callback);
        header('location:'.$url);
    }
	
	
	function lg(){
		session('openid','oYCoAxMNJS1CvOSvjcPAxdka1n00');  
    }
    
   	function lgback(){ 
        $tk = $this->WX->getOauthAccessToken();
        session('openid',$tk['openid']); 
		$toUserToOpenid = session('toUserToOpenid'); 
		if(!empty($toUserToOpenid)){ 
			header('location:/index.php/Kefu/talk/openid/'.$toUserToOpenid);
		}else{
			$this->redirect('Kefu/inlist');
		}
    }
	
	function oper(){
		$this->display();
	}
	
	function kflogin(){
		$this->display();
	}
	 
	function scan(){
		$this->display();
	}
	
	function getjsConf(){
		$url = I('post.url');
		$conf = $this->WX->getJsSign($url);
		$this->_ajax(true,'',$conf);
	} 

	function kflist(){
		$openid = session('openid');
		$this->assign('openid',$openid);
		$this->display();
	}
	
	
	function getkf(){
		$rs = $this->WX->getCustomServiceKFlist();
		P($rs);
	}
	
	function getonlinekf(){
		$rs = $this->WX->getCustomServiceKFlist();
		$online = $this->WX->getCustomServiceOnlineKFlist();
		$ct = array();
		foreach($online['kf_online_list'] as $li){
			$ct[] = $li['kf_account'];
		}
		
		$datlist = array();
		foreach($rs['kf_list'] as $kf){
			if(in_array($kf['kf_account'],$ct)){
				$kf['online'] = 1;
			}else{
				$kf['online'] = 2;
			}
			$datlist[] = $kf;
		}
		
		$this->_ajax(true,'',$datlist);
	}
	
	function createconnect(){
		$openid = I('post.openid');
		$kfaccount = I('post.kf_account');
		$this->WX->createKFSession($openid,$kfaccount,'Connect');
		
		$uMes = array(
			'touser'	=>	$openid,
			'msgtype'	=>	'text',
			'text'	=>	array(
				'content'	=>	'已成功为你对接客服,正在等待客服回复...',
			),
		); 
		$rs = $this->WX->sendCustomMessage($uMes);
		$kf_openid = $openid;
		$kfMes = array(
			'touser'	=>	$kf_openid,
			'msgtype'	=>	'news',
			'news'	=>	array(
				'articles'	=>	array(
					array(
						 "title"		=>	"你好,有人要咨询你",
			             "description"	=>	"在确认你在线的前提下【点击回复】",
			             "url"			=>	"http://weixin.1dospace.com/index.php/kefu/talk/openid/$kf_openid",
			             "picurl" 		=>	"http://wx.qlogo.cn/mmhead/Q3auHgzwzM4g864eib7VoSgWfTRASbIBwCZfOjEqHHm725fVqFssnQA/132" 
					)
				),
			),
		);  
		$this->WX->sendCustomMessage($kfMes);
		
		$this->_ajax(true,'connect OK');
	}
	
	function sendMesOnCloseSession($openid,$ka_account){
	//function sendMesOnCloseSession(){
		/*P($openid,false);
		P($ka_account,false);*/
		$kfUser = M('Kf')->join(' sy_rbac_manager on  sy_rbac_manager.openid = sy_kf.openid ')->where('kf_account="'.$ka_account.'"')->find();
	 	$user = M('Customer')->where(array('openid'=>$openid))->find();

	 	//P($kfUser);
		//发通知信息
		$weObj = new Wechat(C('options'));  
		$data =  array(
			"touser" =>	$openid,
			"template_id" =>	"Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
			"url" =>	"http://sunwayuchoice.com/index.php/Gj/index/openid/".$openid,
			"topcolor" =>	"#FF0000",
			"data" => array( 
					'first'	=>	array(
						"value" =>	"您有一条新的信息通知",
						"color" =>	"#ff0000"
					),
					'keyword1'	=>	array(
						"value" =>	'客服评价',
						"color" =>	"#173177"
					),
					'keyword2'	=>	array(
						"value" =>	'请去评价',
						"color" =>	"#173177"
					),
					'keyword3'	=>	array(
						"value" =>	"您好，请去评价",
						"color" =>	"#173177"
					),
					'remark'	=>	array(
						"value" =>	"尚元云客服平台",
						"color" =>	"#173177"
					)
				)
		);
		//P($data,false);
		$st = $weObj->sendTemplateMessage($data);

		//发站内信息
		//消息模板
		$mesData = array(
			'title'	=>'客服评价',
			'content'	=>'客服评价',
			'type'	=>	1,
			'people'	=>	$kfUser['username'],
			'ctime'	=>	time(),
			'talk_id'=>session('talk_id'),
		);
		//P($mesData,false);
		$mid = M('NoticeContent')->data($mesData)->add();



		$mdata = array(
			'type'=>3,
			'sendtype'=>1,
			'send_name'=> $kfUser['username'],
			'for_apt'=>'',
			'contid'=>$mid,
			'sendtime'=>time(),
			'for_people'=>$user['id'],
			'obj'=>'1',
			
		);
		//P($mdata);
		$mid = M('Notice')->data($mdata)->add();
		
		
	}
	
	function tk(){
		$this->WX->checkAuth();
		P($this->WX->access_token);
	}
		
		
	function index(){
		$this->display();
	}
	
	/**
	* 接入用户列表
	* @return
	*/
	function inlist(){   
		$rs = $this->WX->getKFSessionlist($this->kf_account);  
		$tli = $rs['sessionlist'];
		$arr = array();
		foreach($tli as $li){
			$uin = $this->WX->getUserInfo($li['openid']);

			$uin['key'] = M('kf_tmp_key')->where(array('openid'=>$li['openid']))->find();
			$arr[] = $uin;
		} 
		$this->assign('inlist',$arr);

		$this->assign('kfAccount' , $this->kf_account);
		$this->display();
	}

	public function message()
	{
		$where = "(`from_uid`={$this->user_id} OR `to_uid`={$this->user_id})";
		$sql = "SELECT * FROM (SELECT `id`,`from_uid`,`to_uid`,`msg_type`,`content`,`create_time` as `time` FROM __USER_MESSAGE__ WHERE {$where} ORDER BY `id` DESC) AS m GROUP BY m.from_uid,m.to_uid";
        $model = M();
		$queryList = $model->query($sql);
		$list = [];
        if($queryList){
        	$addTags = [];
            foreach ($queryList as $key => &$row) {
                $only_id = $row['from_uid']>$row['to_uid'] ? $row['to_uid'].'-'.$row['from_uid'] : $row['from_uid'].'-'.$row['to_uid'];
                if(!in_array($only_id, $addTags)){
                	$item = $row;
                	unset($item['id']);
                	$item['nickname'] = '';
                	$item['avatar'] = '';
                	
                	if($item['from_uid'] == $this->user_id){
                		$customerMap = ['id'=>$item['to_uid']];
                	}else{
                		$customerMap = ['id'=>$item['from_uid']];
                		$item['to_uid'] = $item['from_uid'];
                	}
                	unset($item['from_uid']);
                	// 对方用户信息
                	$toCustomer = M('customer')->where($customerMap)->find();
                	if($toCustomer){
                		$toUserInfo = $this->WX->getUserInfo($toCustomer['openid']);
                		if($toUserInfo){
		                	$item['nickname'] = $toUserInfo['nickname'];
		                	$item['avatar'] = $toUserInfo['headimgurl'];
                		}
                	}
                	$list[] = $item;
                	$addTags[] = $only_id;
                }
            }
        }
		$this->assign('list' , $list);
		$this->display();
	}
	
	/**
	* 聊天页面
	* @return
	*/
	function talk(){
		$openid = I('get.openid'); 
		
		$rs = $this->checkKefuLoginStatus();
		if(!$rs){
//			echo "<script>alert('您好，请您先去后台进行客服登录');</script>";exit;
			
			error("您好，请您先去后台进行客服登录","http://sunwayuchoice.com/index.php/Kefu/close_window");
		}
		
		
		$list=M('kf_sc_log')->where('openid="'.$openid.'"')->order('created desc')->find();
		$id=$list['id'];
		session('talk_id',$id);

		$userInfo = $this->WX->getUserInfo($openid);
		
		//mod by liuzm
		$list_user=M('customer')->where('openid="'.$openid.'"')->find();
		$apt_list=M('apt')->where('id="'.$list_user['plot'].'"')->find();
		$apt_name=$apt_list['name'];
		$this->assign('apt_name',$apt_name);
		$this->assign('list_user',$list_user);
		//end		
		
		
		$this->assign('userInfo',$userInfo);
		$this->assign('kf_account',$this->kf_account);
		$kf = M('Kf')->where(array('kf_account'=>$this->kf_account))->find();
		$this->assign('kf_headimg',$kf['kf_headimgurl']);
		$this->assign('stime',time()-3600*2);
		$this->display();
	}
	
	//关闭页面
	public function close_window(){//eixt('111');
		$this->display('close');
	}
	
	
	
	function closeSession(){
		$openid = I('get.openid');
		$rs = $this->WX->closeKFSession($openid,$this->kf_account,'');
		if($rs['errcode']==0){
			$this->sendMesOnCloseSession($openid,$this->kf_account);
			$this->_ajax(true,'成功断开');
		}else{
			$this->_ajax(false,'断开失败');
		}
	}
	
	/**
	* Ajax数据返回
	* @return
	*/
	function _ajax($s,$m,$d){
		$this->ajaxReturn(array('s'=>$s,'m'=>$m,'d'=>$d));
	}
	
	/**
	* 获取接入的用户数据
	* 接口
	* @return
	*/
	function _getinlist(){ 
		$rs = $this->WX->getKFSessionlist($this->kf_account);
		$this->_ajax(true,'OK',$rs);
	}
	
	function sendMes(){
		$openid = I('post.openid');
		$content = I('post.content');
		if(empty($openid) || empty($content)){
			$this->_ajax(true,'缺少必要参数','');
		}
		$rs = $this->_sendMes($openid,$content);
		$this->_ajax(true,'Success',$rs);
	}
	
	/**
	* 发送客服信息
	* @param undefined $openid
	* @param undefined $content
	* 
	* @return
	*/
	function _sendMes($openid,$content){  
		$dat = array(
			'touser'	=>	$openid,
			'msgtype'	=>	'text',
			'text'		=>	array(
				'content'	=>	$content,
			),
			'customservice'	=>	array(
				'kf_account'	=>	$this->kf_account,
			),
		);
		//保存发送日志
		$this->_saveSendLog($openid,$content);
		$rs = $this->WX->sendCustomMessage($dat);
		return $rs;
	}
	
	/**
	* 保存发送日志
	* @param undefined $openid
	* @param undefined $content
	* @return
	*/
	function _saveSendLog($openid,$content){
		$data = array(
			'openid'	=>	$openid,
			'opercode'	=>	2002,
			'text'		=>	$content,
			'time'		=> time(),
			'worker'	=>	$this->kf_account,
		);
		M('Msglog')->data($data)->add();
		/*P(session('kf_account'),false);
		echo M()->_sql();exit('@@@');*/
	}
	
	function getMesLog(){
		ini_set('date.timezone','Asia/Shanghai');
		$openid = I('post.openid');
		$stime = I('post.stime');
		$stime = intval($stime);
		$etime = time();
		
		$rs = $this->_getMesLog($openid,$this->kf_account,$stime,$etime); 

		//获取接收到的数据
		$result = $rs;
		
 		$etime = time();
		$where = ' openid="'.$openid.'" and worker="'.$this->kf_account.'" and time>'.$stime.' and time<= '.$etime;
		$sMes = M('Msglog')->where($where)->select();
		
		$sendMes = array();
		foreach($sMes as $ms){
			$tar = $ms;
			$tar['time'] = intval($ms['time']);
			$tar['opercode'] = intval($ms['opercode']);
			$sendMes[] = $tar;
		}
		
		$result = array_merge($result,$sendMes);
 		
		if(empty($result)){
			$this->_ajax(false,'Empty');
		}
		
		$result = $this->array_sort($result,'time','asc');
		
		$returndata = array();
		foreach($result as $re){
			$returndata[] = $re;
		}
		
		$this->_ajax(true,'Success',array('endtime'=>$etime,'result'=>$returndata));
		
	}
	
	//从服务器获取聊天记录
	function _getMesLog($openid,$worker,$sTime,$etime){ 
		$dat = array(
			'starttime'	=>	$sTime,
			'endtime'	=>	$etime,
			'pageindex'	=>	1,
			'pagesize'	=>	50,
		); 
		//$this->_ajax(false,'Empty',$dat);
		$rs = $this->WX->getCustomServiceMessage($dat); 
		//处理返回数据 
		$returnData = array();
		foreach($rs['recordlist'] as $lin){
			if($openid == $lin['openid'] && $worker == $lin['worker'] ) $returnData[] = $lin;
		}
		return $returnData;
	}
	
	/**
	* 获取用户信息
	* @param undefined $openid
	* @return
	*/
	function _getUserInfo($openid){
		$rs = $this->WX->getUserInfo($openid);
		$this->_ajax(true,'Success',$rs);
	}
	
	function getkf_list(){
		$rs = $this->WX->getCustomServiceKFlist();
		$this->_ajax(true,'OK',$rs);
	}
	
	
	function addkf(){
		$rs = $this->WX->addKFAccount('nicky@test','Nicky','123456');
		$this->_ajax(true,'OK',$rs); 
	}
	
	function getInList(){
		$rs = $this->WX->getKFSessionlist($this->kf_account);
		P($rs,false);
		$rs = $this->WX->getKFSessionWait();
		P($rs);
	}
	
	function saveSendLog($openid,$kf,$text){
		$data = array(
			'openid'	=>	$openid,
			'opercode'	=>	2002,
			'text'		=>	$text,
			'time'		=> time(),
			'worker'	=>	$kf,
		);
		M('Msglog')->data($data)->add();
	}
	
	
	function sort(){
		
		$dat = array(
			array('i'=>4,'d'=>'txt4'),
			array('i'=>2,'d'=>'txt2'),
			array('i'=>6,'d'=>'txt6'),
			array('i'=>1,'d'=>'txt1'),
			array('i'=>5,'d'=>'txt5'),
			array('i'=>3,'d'=>'txt3'),
		);
		
		P($dat,false);
		
		$dat = $this->array_sort($dat,'i','asc'); 
		
		P($dat);
		
	}
	
	function array_sort($arr,$keys,$type='asc'){ 
		 $keysvalue = $new_array = array();
		 foreach ($arr as $k=>$v){
		  	$keysvalue[$k] = $v[$keys];
		 }
		 if($type == 'asc'){
		  	asort($keysvalue);
		 }else{
		  	arsort($keysvalue);
		 }
		 reset($keysvalue);
		 foreach ($keysvalue as $k=>$v){
		  	$new_array[$k] = $arr[$k];
		 }
		 return $new_array; 
	}

	function ls(){
		P($this->kf_account);
		$ls = $this->WX->getKFSessionlist('kf0003@zjit');
		//$ls = $this->WX->getCustomServiceOnlineKFlist('');
		//'oYCoAxNz8Xmj0FKI7LhY6R49Cfuc'
		$rs = $this->WX->closeKFSession('oYCoAxNz8Xmj0FKI7LhY6R49Cfuc','kf0003@zjit','');
		P($ls);
	}
	
	function checkKefuLoginStatus(){
		$kf = M('Kf')->where(array('openid'=>session('openid')))->find();
		$kfAccount = $kf['kf_account'];
		$kfStatus = $this->WX->getCustomServiceOnlineKFlist();
		//P($kfStatus);
		$resturnData = false;
		foreach($kfStatus['kf_online_list'] as $kf){
			if(in_array($kfAccount,$kf)){
				$resturnData = true;
				break;
			}
		}
		return $resturnData;
	}
}
